package webapp.mvc.components;

import com.zoowii.jpa_utils.util.StringUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import webapp.mvc.controllers.HomeController;
import webapp.mvc.exceptions.RedirectException;
import webapp.mvc.exceptions.UserException;
import webapp.mvc.models.UserEntity;
import webapp.mvc.services.IUserService;

import javax.servlet.http.HttpServletRequest;

public class HttpManager {
    private static final Logger LOG = LoggerFactory.getLogger(HttpManager.class);
    
    @Autowired
    private IUserService userService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SiteProperties siteProperties;
    
    public UserEntity currentUser(HttpServletRequest request) throws UserException {
        String username = (String) request.getSession(true).getAttribute("username");
        if(StringUtil.isEmpty(username)) {
            throw new UserException("当前没有登陆");
        }
        UserEntity userEntity = userService.findByUsername(username);
        if(userEntity == null) {
            try {
                userEntity = userService.findOrCreateUserByWechatOpenId(wxMpService, username);
            } catch (UserException e) {
                throw new UserException("找不到用户" + username);
            }
        }
        userEntity.setRoles(userService.getRolesOfUser(userEntity.getId()));
        return userEntity;
    }

    /**
     * 如果是微信中跳转，自动登陆（根据url querystring)
     *
     * @param request
     */
    public void autoLoginOfWechat(HttpServletRequest request) throws RedirectException {
        String openId = request.getParameter(HomeController.WECHAT_AUTOLOGIN_KEY);
        if (openId != null) {
            UserEntity userEntity = null;
            try {
                userEntity = userService.findOrCreateUserByWechatOpenId(wxMpService, openId);
            } catch (UserException e) {
                LOG.error("get user from wechat openid error", e);
                return;
            }
            if (userEntity != null) {
                request.getSession(true).setAttribute("username", userEntity.getUsername());
                request.getSession(true).setAttribute("current_user_id", userEntity.getId());
            }
        }
        String oauthRedirect = request.getParameter(HomeController.WECHAT_OAUTH_KEY);
        if (oauthRedirect != null) {
            if (request.getSession(true).getAttribute("username") == null) {
                String url = wxMpService.oauth2buildAuthorizationUrl(siteProperties.getHost() + "/handle_wechat_oauth_code?redirect=" + oauthRedirect, WxConsts.OAUTH2_SCOPE_BASE, null);
                throw new RedirectException(url);
            }
        }
    }
}
